package com.Shoping.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DbUtils {
	public static DruidDataSource ds;
	public static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	
	static {
		Properties properties = new Properties();
		try {
			properties.load(DbUtils.class.getClassLoader().getResourceAsStream("db.properties"));
			ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		Connection connection = threadLocal.get();
		if(connection==null) {
			try {
				connection = ds.getConnection();
				threadLocal.set(connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return connection;
	}
	
	public void closeAll(Connection connection , Statement statement , ResultSet resultSet) {
		try {
			if(resultSet!=null) {
				resultSet.close();
			}
			if(statement!=null) {
				statement.close();
			}
			if(connection!=null) {
				connection.close();
				threadLocal.remove();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void begin() {
		Connection connection = null;
		try {
			connection = getConnection();
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void commit() {
		Connection connection = null;
		try {
			connection = getConnection();
			connection.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(connection, null, null);
		}
	}
	
	public void rollback() {
		Connection connection = null;
		try {
			connection = getConnection();
			connection.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(connection, null, null);
		}
	}
}